from flask import Blueprint, request, jsonify, g
from app.models import User, APIKey,DoesNotExist
from app.utils import generate_jwt, login_required

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/register', methods=['POST'])
async def register():
    """用户注册"""
    data = request.get_json() or {}
    if not all(k in data for k in ['username', 'password']):
        return jsonify({'error': '用户名和密码为必填项'}), 400
    
    if User.select().where(User.username == data['username']).exists():
        return jsonify({'error': '用户名已存在'}), 400
    
    try:
        user = User(
            username=data['username'],
            email=data.get('email')
        )
        user.set_password(data['password'])
        user.save()
        
        # 自动为新用户生成API Key
        api_key = APIKey(user=user)
        api_key.generate_key()
        api_key.save()
        
        return jsonify({
            'id': user.id,
            'username': user.username,
            'message': '注册成功，请登录'
        }), 201
    except Exception as e:
        return jsonify({'error': f'注册失败：{str(e)}'}), 500

@auth_bp.route('/login', methods=['POST'])
async def login():
    """用户登录"""
    data = request.get_json() or {}
    if not all(k in data for k in ['username', 'password']):
        return jsonify({'error': '用户名和密码为必填项'}), 400
    
    try:
        user = User.get(User.username == data['username'])
        if not user.check_password(data['password']):
            return jsonify({'error': '用户名或密码错误'}), 401
        
        token = generate_jwt(user.id, g.app)
        return jsonify({
            'access_token': token,
            'token_type': 'bearer',
            'user': {
                'id': user.id,
                'username': user.username,
                'is_admin': user.is_admin,
                'avatar': user.avatar
            }
        })
    except User.DoesNotExist:
        return jsonify({'error': '用户名或密码错误'}), 401

@auth_bp.route('/me', methods=['GET'])
@login_required
async def get_current_user():
    """获取当前用户信息"""
    return jsonify({
        'id': g.user.id,
        'username': g.user.username,
        'email': g.user.email,
        'is_admin': g.user.is_admin,
        'avatar': g.user.avatar,
        'created_at': g.user.created_at.isoformat()
    })

@auth_bp.route('/avatar', methods=['POST'])
@login_required
async def upload_avatar():
    """上传用户头像"""
    data = request.get_json() or {}
    if not data.get('avatar_base64'):
        return jsonify({'error': '未提供头像数据'}), 400
    
    try:
        user = g.user
        user.avatar = data['avatar_base64']
        user.save()
        return jsonify({
            'status': 'success',
            'avatar': user.avatar
        })
    except Exception as e:
        return jsonify({'error': f'头像上传失败：{str(e)}'}), 500


@auth_bp.route('/api-keys/get',methods=['POST','GET'])
@login_required
async def get_user_keys():
    try:
        user = g.user    
        return jsonify([{
            'id': k.id,
            'key':k.key,
            'is_active': k.is_active,
            'is_revoked': k.is_revoked,
            'created_at': k.created_at.isoformat()
            } for k in user.api_keys]
        )
    except Exception as e:
        return jsonify(dict(error='unknows msg')),500

@auth_bp.route('/api-keys/create',methods=['POST','GET'])
@login_required
async def create_user_key():
    try:
        # 自动为新用户生成API Key
        api_key = APIKey(user=g.user)
        api_key.generate_key()
        api_key.save()
        
        return jsonify([{
            'id': api_key.id,
            'user_id': api_key.user.id,
            'username': api_key.user.username,
            'description': api_key.description,
            'created_at': api_key.created_at.isoformat()
            } ])

    except Exception as e:
        return jsonify(dict(error='unknows msg')),500

@auth_bp.route('/api-keys/revoke',methods=['POST'])
@login_required
async def revoke_user_key():
    key_id = request.form.get('key_id','')

    try:
        api_key = APIKey.get(
            (APIKey.id == key_id) 
        )
        
        api_key.is_revoked = True
        api_key.save()
        
        return jsonify({'status': 'success', 'message': 'API Key已激活'})
    except DoesNotExist:
        return jsonify({'error': 'API Key不存在或已处理'}), 404

